//
//  SocketAckManager.m
//  Socket.IO-Client
//
//  Created by alanwang.dev on 16/8/8.
//  Copyright © 2016年 com.alanwang.dev. All rights reserved.
//

#import "SocketAckManager.h"

@implementation SocketAck


- (NSInteger)hashValue{
    // TODO: int类型 的哈希值
    //    return [self.ack hash];
    return 0;
}

- (instancetype)init
{
    return [self initWithAck:0 andCallback:nil];
}

- (instancetype)initWithAck:(NSInteger)ack
{
    return [self initWithAck:ack andCallback:nil];
}

- (instancetype)initWithAck:(NSInteger)ack andCallback:(AckCallback)callback
{
    if (self = [super init]) {
        self.ack = ack;
        self.callback = callback;
    }
    return self;
}

- (BOOL)isEqual:(id)object
{
    if (![object isKindOfClass:[SocketAck class]])
        return NO;
    SocketAck *obj = object;
    return self.ack == obj.ack;
}


@end

@implementation SocketAckManager

- (instancetype)init
{
    if (self = [super init]) {
        self.acks = [[NSMutableArray alloc] init];
    }
    return  self;
}

- (void)addAck:(NSInteger)ack callback:(AckCallback)callback
{
    SocketAck *socketAck = [[SocketAck alloc] initWithAck:ack andCallback:callback];
    [self.acks addObject:socketAck];
}

- (void)executeAck:(NSInteger)ack items:(NSArray *)items
{
    SocketAck *socketAck = [[SocketAck alloc] initWithAck:ack];
    if ([self.acks containsObject:socketAck]) {
        NSInteger index = [self.acks indexOfObject:socketAck];
        SocketAck *callback = self.acks[index];
        [self.acks removeObject:callback];
        dispatch_async(dispatch_get_main_queue(),^{callback.callback(items);});
    }
}

- (void)timeoutAck:(NSInteger)ack
{
    SocketAck *socketAck = [[SocketAck alloc] initWithAck:ack];
    if ([self.acks containsObject:socketAck]) {
        NSInteger index = [self.acks indexOfObject:socketAck];
        SocketAck *callback = self.acks[index];
        [self.acks removeObject:callback];
        dispatch_async(dispatch_get_main_queue(),^{callback.callback(@[@"NO ACK"]);});
    }
}

@end
